package com.smalls.redshoes.ui.activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.smalls.newvideotwo.base.BaseActivity;
import com.smalls.newvideotwo.db.Record;
import com.smalls.newvideotwo.db.VodDao;
import com.smalls.newvideotwo.utils.Constant;
import com.smalls.redshoes.R;
import com.smalls.redshoes.adapter.RSVodCategoryContentAdapter;
import com.smalls.redshoes.ui.fragment.LivePlayFragment;
import com.smalls.redshoes.ui.widget.CustomDialog;
import com.smalls.redshoes.ui.widget.GrapeGridview;
import com.smalls.redshoes.ui.widget.RecordDeleteDialog;
import com.smalls.redshoes.util.ActionConfig;
import com.smalls.redshoes.util.AnimationUtil;

import java.util.List;

public class HistoryActivity extends BaseActivity implements View.OnClickListener {
    public static final int CATEGORY_COLLECT = 102;
    public static final int CATEGORY_HISTORY = 101;
    public static final String CATEGORY_SELECT = "category_select";
    private Button btn_delete_all;
    private Button btn_delete_one;
    private GrapeGridview ggv_vod_appoint_content;
    protected ImageLoader imageLoader = ImageLoader.getInstance();
    private boolean isShowDelete = false;
    private int mCategory;
    private RSVodCategoryContentAdapter mContentAdapter;
    protected List<Record> mListProgramModel = null;
    private int mPosition;
    private VodDao mUserVodCollectionDao;
    private View tag;
    private TextView tv_name;
    private TextView tv_total;
    private AdapterView.OnItemClickListener vodOnItemClickListener = new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            if (isShowDelete) {
                if (isHistory()) {
                    mUserVodCollectionDao.deleteRecord(mContentAdapter.getData().get(position));
                } else {
                    mUserVodCollectionDao.deleteRecord(mContentAdapter.getData().get(position));
                }
                mContentAdapter.removeItem(position);
                tv_total.setText(setStringFormat(mListProgramModel.size()));
                return;
            }
            String mid;
            Record item = mContentAdapter.getData().get(position);
            if(isHistory()) {
                if(item.getMovie_id().indexOf("_" + Constant.TYPE_JILU)!=-1) {
                    mid = item.getMovie_id().substring(0, item.getMovie_id().indexOf("_" + Constant.TYPE_JILU));
                } else {
                    mid = item.getMovie_id();
                }
            } else {
                if(item.getMovie_id().indexOf("_" + Constant.TYPE_FAV)!=-1) {
                    mid = item.getMovie_id().substring(0, item.getMovie_id().indexOf("_" + Constant.TYPE_FAV));
                } else {
                    mid = item.getMovie_id();
                }
            }

            Intent intent = new Intent();
            intent.setClass(HistoryActivity.this,VodDetailActivity.class);
            intent.putExtra("get",true);
            intent.putExtra("movie_id",mid);
            intent.putExtra("category_id",item.getCategory_id());
            startActivity(intent);
        }
    };
    private AdapterView.OnItemSelectedListener vodOnItemSelectedListener = new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
            mPosition = position;
            if (isGridViewFocus() && view != null) {
                view.findViewById(R.id.rl_content).setBackgroundResource(R.drawable.rs_vod_content_bg);
                AnimationUtil.scale(view, 1.1f);
            }
            if (view != tag) {
                if (tag != null) {
                    tag.findViewById(R.id.rl_content).setBackgroundResource(0);
                    AnimationUtil.scaleBack(tag, 1.1f);
                }
                tag = view;
            }
        }

        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    };
    private AbsListView.OnScrollListener vodOnScrollListener = new AbsListView.OnScrollListener() {
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            switch (scrollState) {
                case LivePlayFragment.DEFAULT_PROGRAM_INDEX /*0*/:
                    imageLoader.resume();
                    return;
                case 1 /*1*/:
                    imageLoader.pause();
                    return;
                case 2 /*2*/:
                    imageLoader.pause();
                    return;
                default:
                    return;
            }
        }

        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        }
    };


    @Override
    public int onSetContentView() {
        return R.layout.rs_fragment_vod_appoint;
    }

    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.rs_fragment_vod_appoint);
        this.tv_name = (TextView) findViewById(R.id.tv_name);
        this.tv_total = (TextView) findViewById(R.id.tv_total);
        this.btn_delete_one = (Button) findViewById(R.id.btn_delete_one);
        this.btn_delete_all = (Button) findViewById(R.id.btn_delete_all);
        this.ggv_vod_appoint_content = (GrapeGridview) findViewById(R.id.ggv_vod_appoint_content);
        this.mUserVodCollectionDao = new VodDao();
        this.ggv_vod_appoint_content.setSelector(new ColorDrawable(0));
        this.mContentAdapter = new RSVodCategoryContentAdapter(this, this.imageLoader);
    }

    protected void setListener() {
        this.btn_delete_one.setOnClickListener(this);
        this.btn_delete_all.setOnClickListener(this);
        this.ggv_vod_appoint_content.setOnScrollListener(this.vodOnScrollListener);
        this.ggv_vod_appoint_content.setOnItemClickListener(this.vodOnItemClickListener);
        this.ggv_vod_appoint_content.setOnItemSelectedListener(this.vodOnItemSelectedListener);
        this.mContentAdapter.setOnIsShowDelete(new RSVodCategoryContentAdapter.ISShowDelete() {
            public boolean isShowDelete() {
                return isShowDelete;
            }
        });
    }

    public void onResume() {
        super.onResume();
        this.ggv_vod_appoint_content.setAdapter(this.mContentAdapter);
        initTitle();
        initUI();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (isShowDelete()) {
                    setShowDelete();
                    return true;
                }
//                else {
//                    setDeleteFocus(false);
//                    setAppointGridFocus();
//                }
                break;
            case KeyEvent.KEYCODE_DPAD_UP:
                if (isGridViewFocus()) {
                    clearGridItemFocus();
                    requestDeleteOne();
                    return true;
                }
                break;
            case KeyEvent.KEYCODE_DPAD_DOWN:
                if (isGridViewFocus()) {
                    return true;
                }
                if (!isGridViewFocus() && isGridViewOK()) {
                    setGridItemFocus();
                    return true;
                }
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void onPause() {
        super.onPause();
        this.isShowDelete = false;
    }

    public void onStop() {
        super.onStop();
        this.mContentAdapter.clear();
        this.mContentAdapter.notifyDataSetChanged();
        ImageLoader.getInstance().clearMemoryCache();
    }

    public void onHiddenChanged(boolean hidden) {
        //super.onHiddenChanged(hidden);
        if (hidden) {
            this.mContentAdapter.clear();
            this.mContentAdapter.notifyDataSetChanged();
            return;
        }
        initUI();
    }

    private void initTitle() {
        this.mCategory = getIntent().getIntExtra(CATEGORY_SELECT,CATEGORY_HISTORY);
        if (this.mCategory == CATEGORY_HISTORY) {
            ActionConfig.setActionType(8);
            this.tv_name.setText(getResources().getString(R.string.rs_vod_history));
        } else if (this.mCategory == CATEGORY_COLLECT) {
            ActionConfig.setActionType(9);
            this.tv_name.setText(getResources().getString(R.string.rs_vod_collect));
        }
    }

    private void initUI() {
        if (this.mCategory == CATEGORY_HISTORY) {
            this.mListProgramModel = this.mUserVodCollectionDao.queryAlbumByType(Constant.TYPE_JILU);
        } else if (this.mCategory == CATEGORY_COLLECT) {
            this.mListProgramModel = mUserVodCollectionDao.queryAlbumByType(Constant.TYPE_FAV);
        }
        this.mContentAdapter.setData(this.mListProgramModel);
        this.mContentAdapter.notifyDataSetChanged();
        if (this.mListProgramModel != null) {
            this.tv_total.setText(setStringFormat(this.mListProgramModel.size()));
            if (this.mListProgramModel.size() < 1) {
                requestDeleteOne();
                return;
            }
            setDeleteFocus(false);
            setGridItemFocus();
            return;
        }
        this.tv_total.setText(setStringFormat(0));
        requestDeleteOne();
    }

    private String setStringFormat(int num) {
        return String.format(getResources().getString(R.string.rs_vod_total), new Object[]{Integer.valueOf(num)});
    }

    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_delete_all) {
            if (this.mListProgramModel != null && this.mListProgramModel.size() > 0) {
                showDialog();
            }
        } else if (i == R.id.btn_delete_one) {
            if (this.isShowDelete) {
                this.isShowDelete = false;
            } else {
                this.isShowDelete = true;
            }
            this.mContentAdapter.notifyDataSetChanged();
        }
    }

    private void showDialog() {
        final CustomDialog customDialog = CustomDialog.createAndShowDialog(this, R.style.rs_dialog_delete, View.inflate(this, R.layout.rs_dialog_delete_all, null));
        RecordDeleteDialog recordDeleteDialog = new RecordDeleteDialog();
        recordDeleteDialog.setDialog(customDialog, this);
        recordDeleteDialog.setOnDialogClick(new RecordDeleteDialog.OnDialogClick() {
            public void onDialogYesClick() {
                if (isHistory()) {
                    mUserVodCollectionDao.deleteAllByType(Constant.TYPE_JILU);
                } else {
                    mUserVodCollectionDao.deleteAllByType(Constant.TYPE_FAV);
                }
                mContentAdapter.clear();
                customDialog.dismiss();
                tv_total.setText(setStringFormat(mListProgramModel.size()));
            }

            public void onDialogNoClick() {
                customDialog.dismiss();
            }
        });
    }

    public boolean isShowDelete() {
        return this.isShowDelete;
    }

    public void setShowDelete() {
        if (this.isShowDelete) {
            this.isShowDelete = false;
        } else {
            this.isShowDelete = true;
        }
        this.mContentAdapter.notifyDataSetChanged();
    }

    public void clearAdapter() {
        this.mContentAdapter.clear();
    }

    public boolean isHistory() {
        if (this.mCategory == CATEGORY_HISTORY) {
            return true;
        }
        return false;
    }

    public void requestDeleteOne() {
        this.btn_delete_one.setFocusable(true);
        this.btn_delete_all.setFocusable(true);
        this.btn_delete_one.requestFocus();
    }

    public void setDeleteFocus(boolean b) {
        this.btn_delete_one.setFocusable(b);
        this.btn_delete_all.setFocusable(b);
    }

    public int getPosition() {
        return this.mPosition;
    }

    public void setPosition(int position) {
        this.mPosition = position;
    }

    public boolean isGridViewOK() {
        if (this.ggv_vod_appoint_content == null || this.ggv_vod_appoint_content.getCount() <= 0) {
            return false;
        }
        return true;
    }

    public boolean isGridViewFocus() {
        return this.ggv_vod_appoint_content.hasFocus();
    }

    public void clearGridItemFocus() {
        if (this.ggv_vod_appoint_content != null && this.ggv_vod_appoint_content.hasFocus() && this.ggv_vod_appoint_content.getCount() > 0) {
            View view = this.ggv_vod_appoint_content.getSelectedView();
            if (view != null) {
                view.findViewById(R.id.rl_content).setBackgroundResource(0);
                AnimationUtil.scaleBack(view, 1.1f);
                view.setSelected(false);
            }
            unRequestGridViewFocus();
        }
    }

    public void setGridItemFocus() {
        requestGridViewFocus();
        this.ggv_vod_appoint_content.setSelection(this.mPosition);
        View view = this.ggv_vod_appoint_content.getSelectedView();
        if (view != null) {
            view.findViewById(R.id.rl_content).setBackgroundResource(R.drawable.rs_vod_content_bg);
            AnimationUtil.scale(view, 1.1f);
            view.setSelected(true);
            this.tag = view;
        }
    }

    private void requestGridViewFocus() {
        this.ggv_vod_appoint_content.setFocusable(true);
        this.ggv_vod_appoint_content.requestFocus();
    }

    private void unRequestGridViewFocus() {
        this.ggv_vod_appoint_content.clearFocus();
        this.ggv_vod_appoint_content.setFocusable(false);
    }
}
